"""
剪映草稿自动化服务
提供完整的草稿下载和导出HTTP API服务
"""

# 修复COM线程冲突：设置COM为多线程模式
import sys
sys.coinit_flags = 0  # COINIT_MULTITHREADED，允许多线程访问COM对象

import os
import json
import logging
import traceback
import re
import time
import functools
from datetime import datetime
from typing import Dict, Any, Optional
from flask import Flask, request, jsonify
from flask_cors import CORS
import uuid

try:
    # 尝试相对导入（当作为模块使用时）
    from .workflow_manager import WorkflowManager, WorkflowStatus
    from .export_controller import ExportResolution, ExportFramerate
    from .config_manager import get_config
    from .oss_uploader import OSSUploader
except ImportError:
    # 直接导入（当直接运行时）
    from workflow_manager import WorkflowManager, WorkflowStatus
    from export_controller import ExportResolution, ExportFramerate
    from config_manager import get_config
    from oss_uploader import OSSUploader


def performance_monitor(func):
    """性能监控装饰器"""
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        start_time = time.time()
        method_name = func.__name__

        # 记录请求开始
        if hasattr(request, 'method') and hasattr(request, 'path'):
            self.logger.info(f"API调用开始: {request.method} {request.path} -> {method_name}")
        else:
            self.logger.info(f"方法调用开始: {method_name}")

        try:
            result = func(self, *args, **kwargs)

            # 记录成功完成
            end_time = time.time()
            duration = (end_time - start_time) * 1000  # 毫秒
            self.logger.info(f"API调用完成: {method_name}, 耗时: {duration:.2f}ms")

            return result

        except Exception as e:
            # 记录异常
            end_time = time.time()
            duration = (end_time - start_time) * 1000  # 毫秒
            self.logger.error(f"API调用异常: {method_name}, 耗时: {duration:.2f}ms, 错误: {str(e)}")
            raise

    return wrapper


class DraftAutomationService:
    """剪映草稿自动化服务"""

    def __init__(self):
        self.app = Flask(__name__)
        CORS(self.app)  # 允许跨域请求

        # 加载配置
        self.config = get_config()
        self.workflow_manager = WorkflowManager()

        # 初始化OSS上传器
        oss_config = self.config.get_oss_config()
        self.oss_uploader = OSSUploader(oss_config) if oss_config.get('enabled', False) else None

        # 配置日志
        log_level = self.config.get('ui.log_level', 'INFO')
        logging.basicConfig(
            level=getattr(logging, log_level.upper(), logging.INFO),
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        )
        self.logger = logging.getLogger(__name__)

        # 注册路由
        self._register_routes()

    def _extract_draft_name_from_url(self, url: str) -> Optional[str]:
        """从URL中提取草稿名称"""
        try:
            # 匹配 URL 中的草稿ID模式
            # 示例: https://ts.fyshark.com/#/cozeToJianyin?drafId=https://video-snot-12220.oss-cn-shanghai.aliyuncs.com/2025-09-28/draft/a1bc2b29-f873-412e-b4b5-66987965f887.json

            # 查找 .json 前的UUID模式
            pattern = r'/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.json'
            match = re.search(pattern, url)

            if match:
                draft_id = match.group(1)
                self.logger.info(f"从URL中提取到草稿名: {draft_id}")
                return draft_id

            # 如果没有找到UUID模式，尝试其他方式
            # 查找draft/后面的文件名（不含扩展名）
            alt_pattern = r'/draft/([^/]+?)(?:\.json)?(?:\?|$)'
            alt_match = re.search(alt_pattern, url)

            if alt_match:
                draft_id = alt_match.group(1)
                # 移除可能的扩展名
                if draft_id.endswith('.json'):
                    draft_id = draft_id[:-5]
                self.logger.info(f"从URL中提取到草稿名(备选): {draft_id}")
                return draft_id

            self.logger.warning(f"无法从URL中提取草稿名: {url}")
            return None

        except Exception as e:
            self.logger.error(f"提取草稿名异常: {e}")
            return None

    def _upload_to_oss(self, workflow_result: Dict[str, Any], draft_name: str) -> bool:
        """上传完成的文件到OSS"""
        try:
            if not self.oss_uploader:
                return False

            # 获取导出的文件路径
            final_result = workflow_result.get('result', {})
            final_path = final_result.get('final_path')

            if not final_path or not os.path.exists(final_path):
                self.logger.warning("导出文件不存在，跳过OSS上传")
                return False

            self.logger.info(f"开始上传文件到OSS: {final_path}")

            # 上传文件
            upload_result = self.oss_uploader.upload_file(
                local_path=final_path,
                oss_key=f"{draft_name}{os.path.splitext(final_path)[1]}",
                folder="videos"
            )

            if upload_result["success"]:
                # 将OSS信息添加到工作流结果中
                workflow_result["oss_upload"] = {
                    "success": True,
                    "oss_url": upload_result["oss_url"],
                    "oss_key": upload_result["oss_key"],
                    "upload_time": upload_result["upload_time"]
                }
                self.logger.info(f"OSS上传成功: {upload_result['oss_url']}")
                return True
            else:
                workflow_result["oss_upload"] = {
                    "success": False,
                    "message": upload_result["message"]
                }
                self.logger.error(f"OSS上传失败: {upload_result['message']}")
                return False

        except Exception as e:
            error_msg = f"OSS上传异常: {str(e)}"
            self.logger.error(error_msg)
            workflow_result["oss_upload"] = {
                "success": False,
                "message": error_msg
            }
            return False

    def _register_routes(self):
        """注册API路由"""

        @self.app.route('/api/process-draft', methods=['POST'])
        def process_draft():
            """处理剪映草稿 - 下载并导出"""
            return self._process_draft()

        @self.app.route('/api/start-task', methods=['POST'])
        def start_task():
            """启动异步任务"""
            return self._start_task()

        @self.app.route('/api/task-status/<task_id>', methods=['GET'])
        def get_task_status(task_id):
            """获取任务状态"""
            return self._get_task_status(task_id)

        @self.app.route('/api/tasks', methods=['GET'])
        def list_tasks():
            """获取任务列表"""
            return self._list_tasks()

        @self.app.route('/api/unified-tasks', methods=['GET'])
        def list_unified_tasks():
            """获取统一任务列表（包含Worker任务）"""
            return self._list_unified_tasks()

        @self.app.route('/api/cancel-task/<task_id>', methods=['POST'])
        def cancel_task(task_id):
            """取消任务"""
            return self._cancel_task(task_id)

        @self.app.route('/api/download-draft', methods=['POST'])
        def download_draft():
            """仅下载草稿"""
            return self._download_draft()

        @self.app.route('/api/export-draft', methods=['POST'])
        def export_draft():
            """仅导出草稿"""
            return self._export_draft()

        @self.app.route('/api/health', methods=['GET'])
        def health_check():
            """健康检查"""
            return self._health_check()

        @self.app.route('/api/status', methods=['GET'])
        def simple_status():
            """极简状态检查（专为GUI使用，不触发任何UI自动化）"""
            return self._simple_status()

        @self.app.route('/api/cleanup', methods=['POST'])
        def cleanup_tasks():
            """清理已完成的任务"""
            return self._cleanup_tasks()

        @self.app.route('/api/config', methods=['GET'])
        def get_config():
            """获取当前配置"""
            return self._get_config()

        @self.app.route('/api/config', methods=['POST'])
        def update_config():
            """更新配置"""
            return self._update_config()

        @self.app.route('/api/test-oss', methods=['POST'])
        def test_oss():
            """测试OSS连接"""
            return self._test_oss_connection()

    @performance_monitor
    def _process_draft(self) -> tuple:
        """处理剪映草稿 - 异步模式（立即返回任务ID）"""
        try:
            self.logger.info("收到处理草稿请求")

            # 获取请求数据
            data = request.get_json()
            self.logger.info(f"请求数据: {data}")

            # 验证必需参数
            if not data or 'url' not in data:
                error_msg = "缺少必需的参数 'url'"
                self.logger.error(error_msg)
                return jsonify({
                    "success": False,
                    "message": error_msg,
                    "timestamp": datetime.now().isoformat()
                }), 400

            url = data['url'].strip()
            if not url:
                error_msg = "URL不能为空"
                self.logger.error(error_msg)
                return jsonify({
                    "success": False,
                    "message": error_msg,
                    "timestamp": datetime.now().isoformat()
                }), 400

            # 获取COM线程管理器（不检查忙碌状态，允许任务排队）
            try:
                from .com_thread_manager import get_com_thread_manager
            except ImportError:
                from com_thread_manager import get_com_thread_manager
            com_manager = get_com_thread_manager()

            # 记录当前系统状态（用于日志）
            if com_manager.is_system_busy():
                current_task = com_manager.get_current_task()
                self.logger.info(f"系统忙碌中，新任务将排队等待: {url}，当前执行: {current_task}")
            else:
                self.logger.info(f"系统空闲，新任务将立即执行: {url}")

            # 使用配置的默认输出路径
            output_path = self.config.get_output_path()

            # 草稿名：如果用户没有提供，则从URL中自动提取
            draft_name = data.get('draft_name')
            if not draft_name:
                draft_name = self._extract_draft_name_from_url(url)
                if draft_name:
                    self.logger.info(f"自动提取草稿名: {draft_name}")
                else:
                    self.logger.warning("无法从URL提取草稿名，将使用默认名称")

            # 解析分辨率和帧率
            resolution = None
            if 'resolution' in data:
                try:
                    resolution = ExportResolution(data['resolution'])
                except ValueError:
                    return jsonify({
                        "success": False,
                        "message": f"无效的分辨率: {data['resolution']}",
                        "timestamp": datetime.now().isoformat()
                    }), 400

            framerate = None
            if 'framerate' in data:
                try:
                    framerate = ExportFramerate(data['framerate'])
                except ValueError:
                    return jsonify({
                        "success": False,
                        "message": f"无效的帧率: {data['framerate']}",
                        "timestamp": datetime.now().isoformat()
                    }), 400

            # 生成任务ID
            task_id = data.get('task_id', f"task_{uuid.uuid4().hex[:8]}")

            # 提交异步任务到COM线程管理器
            def workflow_task(**kwargs):
                """工作流程任务包装器"""
                try:
                    self.logger.info(f"开始执行工作流程 - 任务ID: {task_id}, URL: {url}")

                    result = self.workflow_manager.execute_workflow(
                        url=url,
                        output_path=output_path,
                        draft_name=draft_name,
                        resolution=resolution,
                        framerate=framerate,
                        task_id=task_id
                    )

                    self.logger.info(f"工作流程执行完成 - 任务ID: {task_id}, 状态: {result.get('status')}")

                    # 如果工作流程成功且启用了OSS，上传文件
                    if result.get("status") == "completed" and self.oss_uploader:
                        self.logger.info(f"开始OSS上传 - 任务ID: {task_id}")
                        self._upload_to_oss(result, draft_name)

                    return result

                except Exception as e:
                    error_msg = f"工作流程执行异常 - 任务ID: {task_id}, 错误: {str(e)}"
                    self.logger.error(error_msg)
                    self.logger.error(f"异常详情: {traceback.format_exc()}")

                    return {
                        "status": "failed",
                        "error": error_msg,
                        "task_id": task_id,
                        "timestamp": datetime.now().isoformat()
                    }

            # 提交任务到COM线程管理器（使用高优先级，避免被GUI检查阻塞）
            try:
                from .com_thread_manager import TaskPriority
            except ImportError:
                from com_thread_manager import TaskPriority

            # 准备传递给COM管理器的参数信息
            task_kwargs = {
                'url': url,
                'output_path': output_path,
                'draft_name': draft_name,
                'resolution': resolution,
                'framerate': framerate,
                'task_id': task_id
            }

            # 提交任务 - 先不传递kwargs给workflow_task，而是单独设置任务的参数信息
            com_manager.submit_task(
                task_id,
                workflow_task,
                args=(),
                kwargs=task_kwargs,  # 传递参数信息用于显示
                priority=TaskPriority.HIGH
            )
            self.logger.info(f"任务已提交到COM线程管理器 - 任务ID: {task_id}, 参数: {task_kwargs}")

            # 立即返回任务信息
            return jsonify({
                "success": True,
                "message": "任务已提交，请使用task_id查询进度",
                "task_id": task_id,
                "status_url": f"/api/task-status/{task_id}",
                "timestamp": datetime.now().isoformat()
            }), 202

        except Exception as e:
            error_msg = f"服务器错误: {str(e)}"
            self.logger.error(error_msg)
            self.logger.error(f"异常详情: {traceback.format_exc()}")
            return jsonify({
                "success": False,
                "message": error_msg,
                "timestamp": datetime.now().isoformat()
            }), 500

    def _start_task(self) -> tuple:
        """启动异步任务"""
        try:
            data = request.get_json()
            if not data or 'url' not in data:
                return jsonify({
                    "success": False,
                    "message": "缺少必需的参数 'url'"
                }), 400

            url = data['url'].strip()
            if not url:
                return jsonify({
                    "success": False,
                    "message": "URL不能为空"
                }), 400

            # 生成任务ID
            task_id = data.get('task_id', f"task_{uuid.uuid4().hex[:8]}")

            # 使用配置的默认输出路径
            output_path = self.config.get_output_path()

            # 草稿名：如果用户没有提供，则从URL中自动提取
            draft_name = data.get('draft_name')
            if not draft_name:
                draft_name = self._extract_draft_name_from_url(url)
                if draft_name:
                    self.logger.info(f"自动提取草稿名: {draft_name}")
                else:
                    self.logger.warning("无法从URL提取草稿名，将使用默认名称")

            resolution = None
            if 'resolution' in data:
                try:
                    resolution = ExportResolution(data['resolution'])
                except ValueError:
                    return jsonify({
                        "success": False,
                        "message": f"无效的分辨率: {data['resolution']}"
                    }), 400

            framerate = None
            if 'framerate' in data:
                try:
                    framerate = ExportFramerate(data['framerate'])
                except ValueError:
                    return jsonify({
                        "success": False,
                        "message": f"无效的帧率: {data['framerate']}"
                    }), 400

            # 创建任务
            task = self.workflow_manager.create_task(
                task_id=task_id,
                url=url,
                output_path=output_path,
                draft_name=draft_name,
                resolution=resolution,
                framerate=framerate
            )

            # 启动任务
            if self.workflow_manager.start_task(task_id):
                return jsonify({
                    "success": True,
                    "task_id": task_id,
                    "message": "任务已启动",
                    "timestamp": datetime.now().isoformat()
                }), 202
            else:
                return jsonify({
                    "success": False,
                    "message": "启动任务失败",
                    "timestamp": datetime.now().isoformat()
                }), 500

        except Exception as e:
            self.logger.error(f"启动任务异常: {e}")
            return jsonify({
                "success": False,
                "message": f"启动任务异常: {str(e)}",
                "timestamp": datetime.now().isoformat()
            }), 500

    @performance_monitor
    def _get_task_status(self, task_id: str) -> tuple:
        """获取任务状态（优先从COM线程管理器获取）"""
        try:
            try:
                from .com_thread_manager import get_com_thread_manager
            except ImportError:
                from com_thread_manager import get_com_thread_manager
            com_manager = get_com_thread_manager()

            # 首先从COM线程管理器获取状态
            com_status = com_manager.get_task_status(task_id)
            if "error" not in com_status:
                # 如果任务已完成，尝试获取详细结果
                if com_status["status"] == "completed" and "result" in com_status:
                    workflow_result = com_status["result"]
                    # 合并COM管理器状态和工作流结果
                    combined_status = {
                        "task_id": task_id,
                        "status": com_status["status"],
                        "created_time": com_status["created_time"],
                        "start_time": com_status["start_time"],
                        "end_time": com_status["end_time"],
                        "workflow_result": workflow_result
                    }
                    return jsonify({
                        "success": True,
                        "data": combined_status,
                        "timestamp": datetime.now().isoformat()
                    }), 200
                else:
                    # 任务还在进行中或失败
                    return jsonify({
                        "success": True,
                        "data": com_status,
                        "timestamp": datetime.now().isoformat()
                    }), 200

            # 如果COM线程管理器中没有，回退到工作流管理器
            workflow_status = self.workflow_manager.get_task_status(task_id)
            if workflow_status is not None:
                return jsonify({
                    "success": True,
                    "data": workflow_status,
                    "timestamp": datetime.now().isoformat()
                }), 200

            # 两边都没有找到任务
            return jsonify({
                "success": False,
                "message": f"任务 {task_id} 不存在",
                "timestamp": datetime.now().isoformat()
            }), 404

        except Exception as e:
            self.logger.error(f"获取任务状态异常: {e}")
            return jsonify({
                "success": False,
                "message": f"获取任务状态异常: {str(e)}",
                "timestamp": datetime.now().isoformat()
            }), 500

    def _list_tasks(self) -> tuple:
        """获取任务列表（增强版，包含详细状态和进度信息）"""
        try:
            try:
                from .com_thread_manager import get_com_thread_manager
            except ImportError:
                from com_thread_manager import get_com_thread_manager
            com_manager = get_com_thread_manager()

            # 获取COM线程管理器的任务
            com_tasks = com_manager.list_tasks(include_completed=True)

            # 获取工作流管理器的任务
            workflow_data = self.workflow_manager.list_tasks()
            workflow_tasks_list = workflow_data.get('tasks', [])

            # 合并任务列表并增强信息
            all_tasks = {}

            # 添加工作流任务
            for task_info in workflow_tasks_list:
                task_id = task_info.get('task_id')
                if task_id:
                    enhanced_task = self._enhance_task_info(task_info, "workflow")
                    all_tasks[task_id] = enhanced_task

            # 添加COM任务（如果有冲突，COM任务优先）
            for task_id, task_info in com_tasks.items():
                enhanced_task = self._enhance_task_info(task_info, "com_manager")
                all_tasks[task_id] = enhanced_task

            # 按创建时间排序
            sorted_tasks = dict(sorted(all_tasks.items(),
                                     key=lambda x: x[1].get('created_time', ''),
                                     reverse=True))

            return jsonify({
                "success": True,
                "data": sorted_tasks,
                "summary": {
                    "total": len(sorted_tasks),
                    "pending": len([t for t in sorted_tasks.values() if t.get('status') == 'pending']),
                    "running": len([t for t in sorted_tasks.values() if t.get('status') == 'running']),
                    "completed": len([t for t in sorted_tasks.values() if t.get('status') == 'completed']),
                    "failed": len([t for t in sorted_tasks.values() if t.get('status') == 'failed']),
                    "cancelled": len([t for t in sorted_tasks.values() if t.get('status') == 'cancelled'])
                },
                "com_status": {
                    "is_busy": com_manager.is_system_busy(),
                    "current_task": com_manager.get_current_task()
                },
                "timestamp": datetime.now().isoformat()
            }), 200

        except Exception as e:
            self.logger.error(f"获取任务列表异常: {e}")
            return jsonify({
                "success": False,
                "message": f"获取任务列表异常: {str(e)}",
                "timestamp": datetime.now().isoformat()
            }), 500

    def _enhance_task_info(self, task_info: dict, source: str) -> dict:
        """增强任务信息，添加详细状态和进度"""
        enhanced = {
            "source": source,
            **task_info
        }

        # 添加调试信息
        self.logger.debug(f"增强任务信息: {task_info.keys()}, source: {source}")

        # 添加任务类型 - 更详细的判断逻辑
        kwargs = task_info.get('kwargs', {})
        args = task_info.get('args', [])

        self.logger.debug(f"判断任务类型 - kwargs: {kwargs}, args: {args}")

        if "url" in task_info or "url" in kwargs or "url" in str(args):
            enhanced["task_type"] = "complete_workflow"
            enhanced["task_type_name"] = "完整流程"
        elif "draft_name" in task_info or "draft_name" in kwargs or any("draft" in str(arg).lower() for arg in args):
            enhanced["task_type"] = "export_only"
            enhanced["task_type_name"] = "仅导出"
        elif source == "com_manager":
            enhanced["task_type"] = "automation_task"
            enhanced["task_type_name"] = "自动化任务"
        else:
            enhanced["task_type"] = "unknown"
            enhanced["task_type_name"] = "未知"

        self.logger.debug(f"任务类型判断结果: {enhanced['task_type_name']}")

        # 解析详细进度状态
        status = task_info.get('status', 'unknown')
        enhanced["progress"] = self._parse_task_progress(task_info, status)

        # 添加显示友好的状态名称
        status_names = {
            'pending': '等待执行',
            'running': '执行中',
            'completed': '已完成',
            'failed': '失败',
            'cancelled': '已取消',
            # 兼容不同来源的状态值
            'PENDING': '等待执行',
            'RUNNING': '执行中',
            'COMPLETED': '已完成',
            'FAILED': '失败',
            'CANCELLED': '已取消'
        }
        enhanced["status_name"] = status_names.get(status, str(status).replace('_', ' ').title())

        # 计算任务持续时间
        try:
            if 'start_time' in task_info and task_info['start_time']:
                start_time_str = task_info['start_time']
                # 处理不同的时间格式
                if isinstance(start_time_str, str):
                    # 移除时区信息简化解析
                    start_time_str = start_time_str.replace('Z', '').replace('+00:00', '')
                    if '.' in start_time_str:
                        start_time = datetime.fromisoformat(start_time_str.split('.')[0])
                    else:
                        start_time = datetime.fromisoformat(start_time_str)

                    if 'end_time' in task_info and task_info['end_time']:
                        end_time_str = task_info['end_time']
                        end_time_str = end_time_str.replace('Z', '').replace('+00:00', '')
                        if '.' in end_time_str:
                            end_time = datetime.fromisoformat(end_time_str.split('.')[0])
                        else:
                            end_time = datetime.fromisoformat(end_time_str)
                        duration = (end_time - start_time).total_seconds()
                    else:
                        duration = (datetime.now() - start_time).total_seconds()

                    enhanced["duration"] = duration
                    enhanced["duration_text"] = self._format_duration(duration)
                else:
                    enhanced["duration"] = 0
                    enhanced["duration_text"] = "-"
            else:
                enhanced["duration"] = 0
                enhanced["duration_text"] = "-"
        except Exception as e:
            self.logger.debug(f"解析时间失败: {e}")
            enhanced["duration"] = 0
            enhanced["duration_text"] = "-"

        # 提取关键参数用于显示
        enhanced["display_params"] = self._extract_display_params(task_info)

        return enhanced

    def _parse_task_progress(self, task_info: dict, status: str) -> dict:
        """解析任务的详细进度状态"""
        progress = {
            "current_stage": "unknown",
            "stages": {
                "downloading": {"status": "pending", "name": "剪映小助手"},
                "exporting": {"status": "pending", "name": "剪映导出"},
                "uploading": {"status": "pending", "name": "OSS上传"},
                "finished": {"status": "pending", "name": "完成"}
            }
        }

        # 根据任务结果分析进度
        if status == "completed":
            # 任务完成，检查具体完成了哪些步骤
            result = task_info.get('result', {})
            if result:
                progress["stages"]["downloading"]["status"] = "completed"
                progress["stages"]["exporting"]["status"] = "completed"

                if result.get('oss_upload', {}).get('success'):
                    progress["stages"]["uploading"]["status"] = "completed"
                    progress["current_stage"] = "finished"
                    progress["stages"]["finished"]["status"] = "completed"
                else:
                    progress["current_stage"] = "uploading"
                    progress["stages"]["uploading"]["status"] = "skipped"
                    progress["current_stage"] = "finished"
                    progress["stages"]["finished"]["status"] = "completed"
        elif status == "running":
            # 任务运行中，需要更细致的状态判断
            progress["stages"]["downloading"]["status"] = "running"
            progress["current_stage"] = "downloading"
        elif status == "failed":
            # 任务失败，标记失败阶段
            progress["stages"]["downloading"]["status"] = "failed"
            progress["current_stage"] = "downloading"
        elif status == "cancelled":
            # 任务取消
            progress["current_stage"] = "cancelled"

        return progress

    def _format_duration(self, seconds: float) -> str:
        """格式化持续时间显示"""
        if seconds < 60:
            return f"{int(seconds)}秒"
        elif seconds < 3600:
            return f"{int(seconds // 60)}分{int(seconds % 60)}秒"
        else:
            hours = int(seconds // 3600)
            minutes = int((seconds % 3600) // 60)
            return f"{hours}小时{minutes}分钟"

    def _extract_display_params(self, task_info: dict) -> dict:
        """提取用于显示的关键参数"""
        params = {}

        # 添加调试日志
        self.logger.debug(f"提取参数 - task_info keys: {list(task_info.keys())}")
        self.logger.debug(f"提取参数 - kwargs: {task_info.get('kwargs', 'None')}")
        self.logger.debug(f"提取参数 - args: {task_info.get('args', 'None')}")

        # 处理直接的参数
        for key in ['url', 'draft_name', 'output_path', 'resolution', 'framerate']:
            if key in task_info:
                value = task_info[key]

                # 特殊处理枚举值
                if hasattr(value, 'value'):  # 枚举对象
                    value = value.value
                elif hasattr(value, 'name'):  # 枚举对象的另一种形式
                    value = value.name

                if key == 'url' and len(str(value)) > 50:
                    params[key] = str(value)[:47] + "..."
                elif key == 'output_path' and len(str(value)) > 30:
                    params[key] = "..." + str(value)[-27:]
                else:
                    params[key] = str(value) if value is not None else None

        # 尝试从args和kwargs中提取参数
        if 'args' in task_info and task_info['args']:
            args = task_info['args']
            if len(args) > 0:
                params['args'] = str(args[0])[:50] + "..." if len(str(args[0])) > 50 else str(args[0])

        if 'kwargs' in task_info and task_info['kwargs']:
            kwargs = task_info['kwargs']
            self.logger.debug(f"kwargs内容: {kwargs}")
            for key in ['url', 'draft_name', 'output_path', 'resolution', 'framerate']:
                if key in kwargs:
                    value = kwargs[key]
                    self.logger.debug(f"从kwargs提取参数 {key}: {value}")

                    # 特殊处理枚举值
                    if hasattr(value, 'value'):  # 枚举对象
                        value = value.value
                    elif hasattr(value, 'name'):  # 枚举对象的另一种形式
                        value = value.name

                    if key == 'url' and len(str(value)) > 50:
                        params[key] = str(value)[:47] + "..."
                    elif key == 'output_path' and len(str(value)) > 30:
                        params[key] = "..." + str(value)[-27:]
                    else:
                        params[key] = str(value) if value is not None else None

        # 如果没有找到任何参数，至少显示任务ID
        if not params and 'task_id' in task_info:
            params['task_id'] = task_info['task_id']

        self.logger.debug(f"最终提取的参数: {params}")
        return params

    def _list_unified_tasks(self) -> tuple:
        """获取统一任务列表（包含Worker任务）"""
        try:
            # 获取基础任务列表
            base_result = self._list_tasks()
            if base_result[1] != 200:
                return base_result

            base_data = base_result[0].get_json()
            if not base_data.get('success'):
                return base_result

            # 获取任务分发器的任务（包含Worker任务）
            unified_tasks = {}
            base_tasks = base_data.get('data', {})

            # 添加基础任务，标记来源为HTTP API
            for task_id, task_info in base_tasks.items():
                task_info['source'] = 'http_api'
                unified_tasks[task_id] = task_info

            # 尝试获取TaskDispatcher的任务
            try:
                from .task_dispatcher import TaskDispatcher

                # 检查是否有可用的TaskDispatcher实例
                # 这里需要找到正确的方式访问TaskDispatcher实例
                # 暂时先返回基础任务，后续可以改进

            except Exception as e:
                self.logger.debug(f"获取TaskDispatcher任务失败: {e}")

            # 计算统计信息
            summary = {
                'total': len(unified_tasks),
                'pending': len([t for t in unified_tasks.values() if t.get('status') in ['pending', 'waiting']]),
                'running': len([t for t in unified_tasks.values() if t.get('status') in ['running', 'processing']]),
                'completed': len([t for t in unified_tasks.values() if t.get('status') == 'completed']),
                'failed': len([t for t in unified_tasks.values() if t.get('status') == 'failed'])
            }

            return jsonify({
                'success': True,
                'data': {
                    'tasks': unified_tasks,
                    'summary': summary
                },
                'message': f'获取到 {len(unified_tasks)} 个任务'
            }), 200

        except Exception as e:
            error_msg = f"获取统一任务列表失败: {str(e)}"
            self.logger.error(error_msg)
            return jsonify({
                'success': False,
                'data': {},
                'message': error_msg
            }), 500

    def _cancel_task(self, task_id: str) -> tuple:
        """取消任务（优先从COM线程管理器取消）"""
        try:
            try:
                from .com_thread_manager import get_com_thread_manager
            except ImportError:
                from com_thread_manager import get_com_thread_manager
            com_manager = get_com_thread_manager()

            # 首先尝试从COM线程管理器取消
            com_success = com_manager.cancel_task(task_id)

            # 然后尝试从工作流管理器取消
            workflow_success = self.workflow_manager.cancel_task(task_id)

            success = com_success or workflow_success

            if success:
                return jsonify({
                    "success": True,
                    "message": f"任务 {task_id} 已取消",
                    "com_cancelled": com_success,
                    "workflow_cancelled": workflow_success,
                    "timestamp": datetime.now().isoformat()
                }), 200
            else:
                return jsonify({
                    "success": False,
                    "message": f"任务 {task_id} 不存在或无法取消",
                    "timestamp": datetime.now().isoformat()
                }), 404

        except Exception as e:
            self.logger.error(f"取消任务异常: {e}")
            return jsonify({
                "success": False,
                "message": f"取消任务异常: {str(e)}",
                "timestamp": datetime.now().isoformat()
            }), 500

    def _download_draft(self) -> tuple:
        """仅下载草稿"""
        try:
            data = request.get_json()
            if not data or 'url' not in data:
                return jsonify({
                    "success": False,
                    "message": "缺少必需的参数 'url'"
                }), 400

            url = data['url'].strip()
            if not url:
                return jsonify({
                    "success": False,
                    "message": "URL不能为空"
                }), 400

            # 执行下载
            result = self.workflow_manager.helper_controller.download_draft(url)

            status_code = 200 if result["success"] else 500
            return jsonify(result), status_code

        except Exception as e:
            self.logger.error(f"下载草稿异常: {e}")
            return jsonify({
                "success": False,
                "message": f"下载草稿异常: {str(e)}",
                "timestamp": datetime.now().isoformat()
            }), 500

    def _export_draft(self) -> tuple:
        """仅导出草稿"""
        try:
            data = request.get_json()
            if not data or 'draft_name' not in data:
                return jsonify({
                    "success": False,
                    "message": "缺少必需的参数 'draft_name'"
                }), 400

            draft_name = data['draft_name'].strip()
            if not draft_name:
                return jsonify({
                    "success": False,
                    "message": "草稿名称不能为空"
                }), 400

            # 获取可选参数
            output_path = data.get('output_path')

            resolution = None
            if 'resolution' in data:
                try:
                    resolution = ExportResolution(data['resolution'])
                except ValueError:
                    return jsonify({
                        "success": False,
                        "message": f"无效的分辨率: {data['resolution']}"
                    }), 400

            framerate = None
            if 'framerate' in data:
                try:
                    framerate = ExportFramerate(data['framerate'])
                except ValueError:
                    return jsonify({
                        "success": False,
                        "message": f"无效的帧率: {data['framerate']}"
                    }), 400

            # 执行导出
            result = self.workflow_manager.export_controller.export_draft(
                draft_name=draft_name,
                output_path=output_path,
                resolution=resolution,
                framerate=framerate
            )

            status_code = 200 if result["success"] else 500
            return jsonify(result), status_code

        except Exception as e:
            self.logger.error(f"导出草稿异常: {e}")
            return jsonify({
                "success": False,
                "message": f"导出草稿异常: {str(e)}",
                "timestamp": datetime.now().isoformat()
            }), 500

    def _health_check(self) -> tuple:
        """健康检查（轻量级，不涉及UI自动化）"""
        try:
            # 导入COM线程管理器
            try:
                from .com_thread_manager import get_com_thread_manager
            except ImportError:
                from com_thread_manager import get_com_thread_manager

            com_manager = get_com_thread_manager()

            # 检查COM线程管理器状态
            com_status = {
                "is_busy": com_manager.is_system_busy(),
                "current_task": com_manager.get_current_task(),
                "active_tasks": len([t for t in com_manager.list_tasks().values() if t["status"] in ["pending", "running"]])
            }

            # 检查控制器初始化状态（不执行实际操作）
            helper_status = {
                "initialized": self.workflow_manager._helper_controller is not None,
                "message": "JianyingHelperController已初始化" if self.workflow_manager._helper_controller is not None else "JianyingHelperController未初始化（懒加载）"
            }

            export_status = {
                "initialized": True,
                "message": "ExportController已初始化"
            }

            return jsonify({
                "status": "healthy",
                "service": "剪映草稿自动化服务",
                "com_manager": com_status,
                "helper_controller": helper_status,
                "export_controller": export_status,
                "tasks": self.workflow_manager.list_tasks(),
                "timestamp": datetime.now().isoformat()
            }), 200

        except Exception as e:
            self.logger.error(f"健康检查异常: {e}")
            return jsonify({
                "status": "unhealthy",
                "error": str(e),
                "timestamp": datetime.now().isoformat()
            }), 500

    @performance_monitor
    def _simple_status(self) -> tuple:
        """极简状态检查（专为GUI使用，不触发任何UI自动化）"""
        try:
            # 只返回最基本的服务状态，不进行任何复杂检查
            return jsonify({
                "status": "ok",
                "service": "Draft Automation Service",
                "timestamp": datetime.now().isoformat()
            }), 200

        except Exception as e:
            return jsonify({
                "status": "error",
                "error": str(e),
                "timestamp": datetime.now().isoformat()
            }), 500

    def _cleanup_tasks(self) -> tuple:
        """清理已完成的任务"""
        try:
            data = request.get_json() or {}
            older_than_hours = data.get('older_than_hours', 24)

            cleaned_count = self.workflow_manager.cleanup_completed_tasks(older_than_hours)

            return jsonify({
                "success": True,
                "message": f"清理了 {cleaned_count} 个任务",
                "cleaned_count": cleaned_count,
                "timestamp": datetime.now().isoformat()
            }), 200

        except Exception as e:
            self.logger.error(f"清理任务异常: {e}")
            return jsonify({
                "success": False,
                "message": f"清理任务异常: {str(e)}",
                "timestamp": datetime.now().isoformat()
            }), 500

    def _get_config(self) -> tuple:
        """获取当前配置"""
        try:
            config_data = self.config.get_all_config()
            # 隐藏敏感信息
            if 'oss' in config_data and 'access_key_secret' in config_data['oss']:
                config_data['oss']['access_key_secret'] = '*' * 8

            return jsonify({
                "success": True,
                "config": config_data,
                "timestamp": datetime.now().isoformat()
            }), 200

        except Exception as e:
            self.logger.error(f"获取配置异常: {e}")
            return jsonify({
                "success": False,
                "message": f"获取配置异常: {str(e)}",
                "timestamp": datetime.now().isoformat()
            }), 500

    def _update_config(self) -> tuple:
        """更新配置"""
        try:
            data = request.get_json()
            if not data:
                return jsonify({
                    "success": False,
                    "message": "缺少配置数据",
                    "timestamp": datetime.now().isoformat()
                }), 400

            # 更新配置
            if self.config.update_config(data):
                if self.config.save_config():
                    # 重新初始化OSS上传器
                    oss_config = self.config.get_oss_config()
                    if oss_config.get('enabled', False):
                        self.oss_uploader = OSSUploader(oss_config)
                    else:
                        self.oss_uploader = None

                    return jsonify({
                        "success": True,
                        "message": "配置更新成功",
                        "timestamp": datetime.now().isoformat()
                    }), 200
                else:
                    return jsonify({
                        "success": False,
                        "message": "保存配置失败",
                        "timestamp": datetime.now().isoformat()
                    }), 500
            else:
                return jsonify({
                    "success": False,
                    "message": "更新配置失败",
                    "timestamp": datetime.now().isoformat()
                }), 500

        except Exception as e:
            self.logger.error(f"更新配置异常: {e}")
            return jsonify({
                "success": False,
                "message": f"更新配置异常: {str(e)}",
                "timestamp": datetime.now().isoformat()
            }), 500

    def _test_oss_connection(self) -> tuple:
        """测试OSS连接"""
        try:
            if not self.oss_uploader:
                return jsonify({
                    "success": False,
                    "message": "OSS未配置或未启用",
                    "timestamp": datetime.now().isoformat()
                }), 400

            test_result = self.oss_uploader.test_oss_connection()
            status_code = 200 if test_result["success"] else 500

            return jsonify({
                "success": test_result["success"],
                "message": test_result["message"],
                "bucket_info": test_result.get("bucket_info"),
                "timestamp": datetime.now().isoformat()
            }), status_code

        except Exception as e:
            self.logger.error(f"测试OSS连接异常: {e}")
            return jsonify({
                "success": False,
                "message": f"测试OSS连接异常: {str(e)}",
                "timestamp": datetime.now().isoformat()
            }), 500

    def run(self, host='0.0.0.0', port=5000, debug=False):
        """启动服务"""
        # 记录详细的启动日志
        self.logger.info("剪映草稿自动化服务正在启动...")
        self.logger.info(f"服务配置: host={host}, port={port}, debug={debug}")

        # 记录配置信息
        output_path = self.config.get_output_path()
        oss_config = self.config.get_oss_config()
        self.logger.info(f"输出路径: {output_path}")
        self.logger.info(f"OSS配置: {'已启用' if oss_config.get('enabled') else '未启用'}")

        # 初始化COM线程管理器
        try:
            from .com_thread_manager import get_com_thread_manager
        except ImportError:
            from com_thread_manager import get_com_thread_manager

        com_manager = get_com_thread_manager()
        self.logger.info("COM线程管理器已初始化")

        print("剪映草稿自动化服务启动")
        print("=" * 60)
        print("可用接口:")
        print("  POST /api/process-draft      - 完整处理流程（下载+导出）")
        print("  POST /api/start-task         - 启动异步任务")
        print("  GET  /api/task-status/<id>   - 获取任务状态")
        print("  GET  /api/tasks              - 获取任务列表")
        print("  POST /api/cancel-task/<id>   - 取消任务")
        print("  POST /api/download-draft     - 仅下载草稿")
        print("  POST /api/export-draft       - 仅导出草稿")
        print("  GET  /api/health             - 健康检查")
        print("  GET  /api/status             - 轻量级状态检查（GUI专用）")
        print("  POST /api/cleanup            - 清理已完成任务")
        print("=" * 60)
        print("使用示例:")
        print('  # 完整流程')
        print('  curl -X POST http://localhost:5000/api/process-draft \\')
        print('       -H "Content-Type: application/json" \\')
        print('       -d \'{"url": "https://example.com/draft", "output_path": "C:/exports/"}\'')
        print()
        print('  # 异步任务')
        print('  curl -X POST http://localhost:5000/api/start-task \\')
        print('       -H "Content-Type: application/json" \\')
        print('       -d \'{"url": "https://example.com/draft", "draft_name": "我的草稿"}\'')
        print("=" * 60)
        print(f"服务地址: http://{host}:{port}")
        print("日志级别:", self.logger.level)
        print()

        self.logger.info(f"服务启动完成，监听地址: http://{host}:{port}")

        try:
            self.app.run(host=host, port=port, debug=debug)
        except Exception as e:
            self.logger.error(f"服务运行异常: {e}")
            self.logger.error(f"异常详情: {traceback.format_exc()}")
            raise


def main():
    """主函数"""
    service = DraftAutomationService()
    service.run()


if __name__ == '__main__':
    main()